package database;

import Entity.User;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author BinhNV_A04911
 */
public class UserManagerDB {

    private CallableStatement cstmt;
    private java.sql.Connection conn;
    private ResultSet rs;

    public UserManagerDB(java.sql.Connection conn) {
        this.conn = conn;
    }

    public void loadData(User userManager) {
        try {
            cstmt = conn.prepareCall("{call sp_GetUser}");
            rs = cstmt.executeQuery();
            while (rs.next()) {

                String username = rs.getString("Username");
                String passWord = rs.getString("PassWord");
                String authorID = rs.getString("AuthorID");
                String fullName = rs.getString("FullName");
                String gender = rs.getString("Gender");
                boolean status = rs.getBoolean("Status");
                User ur = new User(username, passWord, authorID, fullName, gender, status);
                userManager.add(ur);
            }
            rs.close();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void deleteUser(User obj) {
        try {
            cstmt = conn.prepareCall("{call sp_DeleteUser(?)}");
            cstmt.setInt(1, obj.getUsername());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void insertUser(User obj) {
        try {
            cstmt = conn.prepareCall("{call sp_InsertUser(?,?,?,?,?,?)}");
            cstmt.setInt(1, obj.getUsername());
            cstmt.setString(2, obj.getPassWord());
            cstmt.setString(3, obj.getAuthorID());
            cstmt.setString(4, obj.getFullName());
            cstmt.setString(5, obj.getGender());
            boolean status = rs.getBoolean("Status");
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateUser(User obj) {
        try {
           cstmt = conn.prepareCall("{call sp_InsertUser(?,?,?,?,?,?)}");
            cstmt.setInt(1, obj.getUsername());
            cstmt.setString(2, obj.getPassWord());
            cstmt.setString(3, obj.getAuthorID());
            cstmt.setString(4, obj.getFullName());
            cstmt.setString(5, obj.getGender());
            boolean status = rs.getBoolean("Status");
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
